<template>
  <div class="app-container">
    <!-- 输入表单 -->
    <el-form label-width="120px" :inline="true">
      <el-form-item label="教练名称">
        <el-input v-model="trainer.trName" style="width: 220px"/>
      </el-form-item>
      <el-form-item label="教练性别">
        <el-select v-model="trainer.gender" style="width: 100px">
          <el-option :value="0" label="女"/>
          <el-option :value="1" label="男"/>
        </el-select>
      </el-form-item>
    </el-form>
    <el-form label-width="120px" :inline="true">
      <el-form-item label="教练年龄">
        <el-input v-model="trainer.age" style="width: 50px"/>
      </el-form-item>
      <el-form-item label="从业年限">
        <el-input v-model="trainer.career" style="width: 50px"/>
      </el-form-item>
      <el-form-item label="擅长方向">
        <el-cascader
          clearable
          :show-all-levels="false"
          v-model="cascaderList"
          :options="categoryList"
          :props="{ expandTrigger: 'hover',multiple : 'true'}"
          @change="handleChange"></el-cascader>
      </el-form-item>
    </el-form>
    <el-form label-width="120px" :inline="true">
      <el-form-item label="教练电话">
        <el-input v-model="trainer.phone" style="width: 220px"/>
      </el-form-item>
      <el-form-item label="教练身份证号">
        <el-input v-model="trainer.idNo" style="width: 220px"/>
      </el-form-item>
      <el-form-item label="教练生日">
        <el-date-picker v-model="trainer.birthday" type="date" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd"/>
      </el-form-item>
    </el-form>
    <el-form label-width="120px">
      <el-form-item label="教练简介">
        <el-input type="textarea" v-model="trainer.intro" :rows="6" style="width: 60%"></el-input>
      </el-form-item>
      <!-- 教练头像 -->
      <el-form-item label="教练头像">
        <el-upload
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :on-error="handleAvatarError"
          :action="BASE_API+'/file/uploadInAdmin'"
          :data="UPLOADFILEBIZ"
          :headers="headers"
          name="avatar"
          class="avatar-uploader"
        >
          <img v-if="trainer.avatar" :src="trainer.avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"/>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveOrUpdate()">保存</el-button>
        <el-button v-show="canIdentify" type="success" @click="handleIdentify()">认证</el-button>
      </el-form-item>
    </el-form>


  </div>
</template>

<script>
import trainerAPI from '@/api/trainer'
import {getToken} from '@/utils/auth' // get token from cookie
import categoryAPI from '@/api/category'

export default {
  data() {
    return {
      categoryList: [],
      cascaderList: [],
      ISIDENTIFIED: 1,
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      headers: {
        'token': getToken()
      },
      UPLOADFILEBIZ: {biz: 'trainer_avatar'},
      canIdentify: false, // 是否可用认证按钮
      BASE_API: 'http://localhost:8099',
      // 初始化教练默认数据
      trainer: {
        cascaderList: [],
        expertiseList: []
      },
      saveBtnDisabled: false // 保存按钮是否禁用，防止表单重复提交
    }
  },
  // 页面渲染成功
  created() {
    categoryAPI.getCategoryCascader().then(res => {
      this.categoryList = res.data
    })
    if (this.$route.params.id) {
      this.fetchDataById(this.$route.params.id)
    }
  },
  methods: {
    handleChange(val) {
      if (Array.isArray(val)) {
        this.trainer.expertiseList = []
        for (let i = 0; i < val.length; i++) {
          this.trainer.expertiseList.push(val[i].slice(-1).toString())
        }
      }
      // this.trainer.expertise = val.slice(-1).toString()
      // this.cascaderList.push(this.searchObj.expertise)
      console.log(this.cascaderList)
      console.log(this.trainer.expertiseList)
    },
    fetchDataById(id) {
      trainerAPI.getTrainerById(id).then(res => {
        this.trainer = res.data
        this.canIdentify = this.trainer.isIdentified === 0
        for (let i = 0; i < this.trainer.expertiseList.length; i++) {
          let child = []
          child.push(this.trainer.expertiseList[i].parentId)
          child.push(this.trainer.expertiseList[i].id)
          this.cascaderList.push(child)
        }
        this.handleChange(this.cascaderList)
        // console.log(this.cascaderList)
      })
    },


    createCascader(expertiseList) {
      let cascaders = {children: []}
      cascaders.value = expertiseList[0].parentId
      cascaders.label = expertiseList[0].parentName
      for (let i = 0; i < expertiseList.length; i++) {
        let child = {value: expertiseList[i].id, label: expertiseList[i].categoryName}
        cascaders.children.push(child)
      }
      return cascaders
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = this.trainer.avatar
      this.dialogVisible = true
    },
    // 新增教练
    saveData() {
      trainerAPI.saveTrainer(this.trainer).then(response => {
        this.$message({
          type: 'success',
          message: '新增成功！'
        })
        this.$router.push({path: '/trainer/list'})
      })
    },
    // 根据id更新记录
    updateData() {
      trainerAPI.updateById(this.trainer.id, this.trainer).then(response => {
        this.$message({
          type: 'success',
          message: '修改成功！'
        })
        this.$router.push({path: '/trainer/list'})
      })
    },
    handleIdentify() {
      this.$confirm('是否已经确认信息无误！', '认证教练', {
        distinguishCancelAndClose: true,
        cancelButtonText: '取消',
        confirmButtonText: '确定认证'
      }).then(() => {
        trainerAPI.IdentifyEmpById(this.trainer.id, this.ISIDENTIFIED).then(res => {
          this.trainer.isIdentified = this.ISIDENTIFIED
          this.fetchDataById(this.trainer.id)
          this.$message.success('认证成功！')
        })
      }).catch(action => {
        this.$message({
          type: 'info',
          message: '取消删除'
        })
      })
    },
    saveOrUpdate() {
      // 禁用保存按钮
      this.saveBtnDisabled = true
      if (!this.trainer.id) {
        this.saveData()
      } else {
        this.updateData()
      }
    },
    // 上传校验
    beforeAvatarUpload(file) {
      console.log(file)
      const isJPG = file.type === 'image/jpeg' || 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 上传成功回调
    handleAvatarSuccess(res, file) {
      if (res.code === 20000) {
        // console.log(res)
        this.trainer.avatar = res.data
        // 强制重新渲染
        this.$forceUpdate()
      } else {
        this.$message.error('上传失败 （非0）')
      }
    },
    // 错误处理
    handleAvatarError() {
      console.log('error')
      this.$message.error('上传失败（http失败）')
    },
    handleRemove(file) {
      console.log(file)
    },

  }
}
</script>

<style scoped>
.avatar-uploader .avatar-uploader-icon {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar-uploader .avatar-uploader-icon:hover {
  border-color: #409EFF;
}

.avatar-uploader img {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
